import { h } from "koishi"

export const name = "-lnnbot-admin-locale-validate"

export function apply(ctx) {
  function formatLocaleList(session) {
    const localeNames = ctx.i18n.get("general.name")
    const out = []
    out.push(...session.i18n(["lnnbot.admin.available-locales"]))
    for (const locale of ctx.root.config.i18n.locales) {
      if (Object.hasOwn(localeNames, locale))
        out.push(h("p", [h("b", locale), " - ", ...ctx.i18n.render([locale], ["general.name"])]))
    }
    return out
  }

  ctx.command("-lnnbot-list-locales", { hidden: true })
    .alias("user.locale.list")
    .alias("channel.locale.list")
    .action(({ session }) => formatLocaleList(session))

  ctx.on("command/before-execute", async ({ command, session, args }) => {
    if (!["user.locale", "channel.locale"].includes(command.name)) return
    if (args[0] && !ctx.root.config.i18n.locales.includes(args[0])) {
      const out = formatLocaleList(session)
      if (args[0] !== "list") out.unshift(...session.i18n("lnnbot.admin.invalid-locale"))
      return out
    }
  })

  ctx.i18n.define("zh-CN", {
    lnnbot: {
      admin: {
        "invalid-locale": "语言代码无效。",
        "available-locales": "可用的语言有：",
      },
    },
    commands: {
      "-lnnbot-list-locales": {
        description: "显示可用的语言",
      },
    },
  })
}
